<?php
abstract class Vs_Table
	extends Zend_Db_Table_Abstract 
	
{
	protected function _now()
	{
		return date("Y:m:d H:i:s");
	}
	
	protected function _fecha( $data, $fechaCreacion, $fechaModificacion )
	{
		if ( $fechaCreacion ){
			$data['fechaCreacion'] = $this->_now();
		}
		
		if ( $fechaModificacion ){
			$data['fechaModificacion'] = $this->_now();
		}
		
		return $data;
	}
	
	protected function _whereVal($select, $col, $val, $type=Zend_Db::INT_TYPE)
	{
	    if ( is_array($val)){
			$select->where("{$col} IN(?)", $val, $type);
		} else {
		    $select->where("{$col} = ?", $val, $type);
		}
	    
	}
	
	public function getByids( $ids )
	{
	    return $this->getByParams( array( 
	        $this->_getPrimaryName() => $ids
	    ));
	}
	
	public function getByParams( $params, $offset = null, $limit = null, $order = null )
	{
		$select = $this->select();
		
		if ( $order ){
			$select->order( $order );
		}
		
		if ( $limit && !is_null($offset) ){
			$select->limit( $limit, $offset );
		}
		
		foreach ($this->_keys as $col=>$type){
    		if ( isset($params[$col])){
    			$this->_whereVal($select, $col, $params[$col], $type);
    		}
		}
		return $this->_db->fetchAssoc($select);
	}
	
	public function countByParams( $params )
	{
		$select = $this->select()
				->from($this, array('count' => 'COUNT(1)'));
		
        foreach ($this->_keys as $col=>$type){
    		if ( isset($params[$col])){
    			$this->_whereVal($select, $col, $params[$col], $type);
    		}
		}
		
		$result = $this->_db->fetchRow($select);
		
		return $result['count'];
	}
	
	protected function _getData( $entity )
	{
	    $data = array_intersect_key(
	        (array) $entity, 
	        $this->_keys);
	    
	    foreach($this->_nulls as $key){
	    	if (empty($data[$key])){
	    		$data[$key] = new Zend_Db_Expr("NULL");
	    	}
	    }
	    return $data;
	}
	
	protected function _getPrimaryName()
	{
	    return is_array($this->_primary) ? current($this->_primary) : $this->_primary;
	}
	
	public function insert( $entity )
	{
		return parent::insert( 
			$this->_getData( $entity )	
		);	
	}
	
	public function update( $entity )
	{
		return parent::update( 
			$this->_getData( $entity ),
			array($this->_getPrimaryName() .'=?' => $entity->getId())	
		);	
	}
	
	public function delete( $entity )
	{
		return parent::delete(
			array( $this->_getPrimaryName() .'=?' => $entity->getId())
		);
	}
	
	
}
